package com.aaa.vegetablemarketexpress.controller;

import com.aaa.vegetablemarketexpress.entity.Customer;
import com.aaa.vegetablemarketexpress.entity.User;
import com.aaa.vegetablemarketexpress.service.CustomerService;
import com.aaa.vegetablemarketexpress.service.UserService;
import com.aaa.vegetablemarketexpress.util.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @FileName: CustomerController
 * @Description: 客户控制器
 * @Author: qxh
 * @CreateTime: 2025/9/10
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("/customer")
@Log4j2
public class CustomerController {
    @Resource
    private UserService userService;
    @Resource
    private HttpSession session;
    @Resource
    private CustomerService customerService;
/*    // 在类中添加属性
    @Value("${file.upload.id-photo-path}")
    private String idPhotoSavePath;//文件保存路径
    @Value("${file.access.prefix}")
    private String fileAccessPrefix;//文件访问前缀*/

    /**
     * 查询客户信息
     * @param customerId
     * @return
     */
    @PostMapping("selectCustomerById")
    public Result selectCustomerById(Long customerId) {
        log.info("查询客户信息");
        return ResultUtil.success(customerService.selectCustomerById(customerId));
    }

    /**
     * 查询客户列表
     * @param page
     * @return
     */
    @PostMapping("selectCustomerList")
    public Result selectCustomerList(@RequestBody Page<Customer> page) {
        log.info("查询客户列表");
        return ResultUtil.success(customerService.selectCustomerList(page));
    }

    /**
     * 添加客户
     * @param customer
     * @return
     */
    @PostMapping("insertCustomer")
    public Result insertCustomer(@RequestBody Customer customer) {
        log.info("添加客户");
        return ResultUtil.success(customerService.insertCustomer(customer));
    }

    /**
     * 修改客户
     * @param customer
     * @return
     */
    @PostMapping("updateCustomer")
    public Result updateCustomer(@RequestBody Customer customer) {
        log.info("修改客户");
        return ResultUtil.success(customerService.updateCustomer(customer));
    }

    /**
     * 删除客户
     * @param customerId
     * @return
     */
    @DeleteMapping("deleteCustomerById")
    public Result deleteCustomerById(Long customerId) {
        log.info("删除客户");
        return ResultUtil.success(customerService.deleteCustomerById(customerId));
    }

    /**
     * 检查手机号是否唯一
     * @param customer
     * @return
     */
    @PostMapping("checkPhoneUnique")
    public Result checkPhoneUnique(@RequestBody Customer customer) {
        log.info("检查手机号是否唯一");
        return ResultUtil.success(customerService.checkPhoneUnique(customer));
    }

    /**
     * 审核客户
     * @param customer
     * @return
     */
    @PostMapping("auditCustomer")
    public Result auditCustomer(@RequestBody Customer customer) {
        log.info("审核客户，客户ID: {}", customer.getCustomerId());
        try {
            int result = customerService.auditCustomer(customer);
            if (result > 0) {
                log.info("客户审核成功，客户ID: {}", customer.getCustomerId());
                return ResultUtil.success("客户审核成功");
            } else {
                log.warn("客户审核失败");
                return ResultUtil.failed("客户审核失败");
            }
        } catch (Exception e) {
            log.error("客户审核时发生异常", e);
            return ResultUtil.failed("客户审核失败: " + e.getMessage());
        }
    }


    /**
     * 根据登录用户ID查询商家（客户）注册及审核状态
     * @return 包含审核状态的结果
     */
    @PostMapping("getMerchantStatus")
    public Result getMerchantStatus() {
        log.info("查询当前用户的商家注册状态");
        try {
            // 从Session获取登录用户信息（需确保登录拦截器已生效）
            User loginUser = (User) session.getAttribute("userInfo");
            if (loginUser == null) {
                return ResultUtil.failed("用户未登录");
            }
            // 调用Service查询关联的客户（商家）信息
            Customer merchant = customerService.selectCustomerByUserId(loginUser.getUserId());
            if (merchant == null) {
                // 未提交过注册申请
                return ResultUtil.success(new HashMap<String, Object>() {{
                    put("hasApplied", false); // 是否提交过申请
                    put("status", ""); // 审核状态（空表示未申请）
                    put("merchantInfo", null); // 商家信息（空）
                }});
            }
            // 转换审核状态为前端易理解的枚举（0=待审核，1=通过，2=拒绝）
            String statusDesc = switch (merchant.getAuditStatus()) {
                case "0" -> "pending";
                case "1" -> "approved";
                case "2" -> "rejected";
                default -> "";
            };
            // 构造返回数据
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("hasApplied", true);
            resultData.put("status", statusDesc);
            resultData.put("merchantInfo", new HashMap<String, Object>() {{
                put("customerName", merchant.getCustomerName());
                put("idCard", merchant.getIdCard());
                put("phone", merchant.getPhone());
                put("address", merchant.getAddress());
                put("idPhotograph", merchant.getIdPhotograph());
                put("auditStatus", statusDesc);
                put("auditRemark", merchant.getAuditRemark());
                put("auditTime", merchant.getAuditTime() != null ?
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(merchant.getAuditTime()) : "");
            }});
            return ResultUtil.success(resultData);
        } catch (Exception e) {
            log.error("查询商家状态异常", e);
            return ResultUtil.failed("查询失败：" + e.getMessage());
        }
    }



    /**
     * 上传身份证照片
     * @param
     * @return
     */
/*    @PostMapping("/uploadIdPhoto")
    public Result uploadIdPhoto(@RequestParam("file") MultipartFile file) {
        // 获取项目根路径并构建保存路径
        String projectPath = System.getProperty("user.dir");
        String fullPath = projectPath + "/" + idPhotoSavePath;

        if (file.isEmpty()) {
            return ResultUtil.failed("上传文件为空");
        }

        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || (!originalFilename.endsWith(".jpg") && !originalFilename.endsWith(".png"))) {
            return ResultUtil.failed("上传文件格式错误");
        }

        // 检查文件大小（不超过2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            return ResultUtil.failed("上传文件过大");
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "_" + originalFilename;

        try {
            // 创建目录（如果不存在）
            Path path = Paths.get(fullPath);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }

            // 保存文件
            Path filePath = Paths.get(fullPath + fileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 构造访问URL
            String accessUrl = fileAccessPrefix + "id-photo/" + fileName;

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            Map<String, String> data = new HashMap<>();
            data.put("url", accessUrl);
            result.put("url", accessUrl);
            result.put("data", data);

            log.info("身份证照片上传成功，文件名：{}", fileName);

            return ResultUtil.success(result);
        } catch (Exception e) {
            log.error("身份证照片上传失败", e);
            return ResultUtil.failed("身份证照片上传失败: " + e.getMessage());
        }
    }*/
    @PostMapping("selectCustomerListAndStatus")
    public Result selectCustomerListAndStatus(@RequestBody Page<Customer> page) {
        log.info("查询客户列表");
        return ResultUtil.success(customerService.selectCustomerListAndStatus(page));
    }
    /**
     * 上传身份证照片
     * @param file
     * @return
     */
    @PostMapping("/uploadIdImage")
    public Result uploadIdImage(@RequestParam("pic") MultipartFile file) {
        //调用工具类，进行上传
        return ResultUtil.success(OssUtil.uploadFile("id/images",file));
    }

}
